package edu.ntu.im.p2ptrade;

import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import net.jxta.pipe.PipeService;
import net.jxta.protocol.PipeAdvertisement;
import net.jxta.util.JxtaBiDiPipe;
import net.jxta.util.JxtaServerPipe;

public class DialogServer implements Runnable{
	JxtaServerPipe serverPipe;
	public DialogServer() throws IOException {
//		PipeAdvertisement padv = PipeUtil.createAdv(P2PTrade.p2pTrade.peerGroup, P2PTrade.p2pTrade.getPipeName(), PipeService.UnicastType);
//		System.out.println(padv);
		byte[] bid = null;
		try {
			 bid= MessageDigest.getInstance("MD5").digest(
					"abcd".getBytes("ISO-8859-1"));
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		serverPipe = new JxtaServerPipe(P2PTrade.getInstance().getPeerGroup(),PipeUtil.getAdv(P2PTrade.getInstance().getAppPeerGroup(), P2PTrade.getInstance().getPipeName(), PipeService.UnicastType, bid));
        serverPipe.setPipeTimeout(0);
	}
	public class ConnectionHandler implements Runnable{
		private JxtaBiDiPipe pipe;
		public ConnectionHandler(JxtaBiDiPipe pipe){
			this.pipe = pipe;
			pipe.setMessageListener(DialogHost.getInstance());
		}
		public void run() {
			DialogHost.getInstance().addPipe(Util.toNormalName(pipe.getRemotePeerAdvertisement().getName()), pipe);
			System.out.println(" [  connect to peer [" +pipe.getRemotePeerAdvertisement().getName() +"]");
		}
	}
	public void run() {
		System.out.println("dialog server runned");
		while (true){
			try {
				JxtaBiDiPipe pipe = this.serverPipe.accept();
				
				new Thread(new ConnectionHandler(pipe)).start();
				
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
	}

}
